package com.gxuwz.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.gxuwz.model.Academy;

/**
 * 使用XML读出URL时存在转码问题(先直接从数据库读URL)
 * 
 * @author h
 * 
 */
public class AcademyXml {

	/**
	 * 写入数据到XML中
	 * 
	 * @param academys
	 * @throws IOException
	 */
	public static void write(List<Academy> academys) throws IOException {
		// 创建一个文档对象
		Document document = DocumentHelper.createDocument();

		// 构造dom树
		Element roote = document.addElement("academys");

		for (Academy academy : academys) {
			Element child = roote.addElement("academy");
			child.addElement("id").addText(String.valueOf(academy.getId()));
			child.addElement("academyName").addText(academy.getAcademyName());
			child.addElement("academyURL").addText(academy.getAcademyURL());
		}

		// 设置字符编码方式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("gbk");

		// 开始写
		XMLWriter xmlWriter = new XMLWriter(new FileWriter("academy.xml"),
				format);
		xmlWriter.write(document);
		xmlWriter.close();
	}

	public static String[] read() {
		// 创建解析对象
		SAXReader reader = new SAXReader();

		String values[] = null;
		List<String> list = new ArrayList<>();

		// 读取XML文件
		Document document;

		try {
			document = reader.read(new File("academy.xml"));
			// 获取根节点下面的子节点
			List<?> nodes = document.selectNodes("/academys/academy");

			for (Iterator<?> it = nodes.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				// System.out.println(elm.element("academyURL").getText().replaceAll("[\r\n]",""));
				list.add(elm.element("academyURL").getText().toString()
						.replaceAll("[\r\n]", ""));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 获取根节点
		// Element roote = document.getRootElement();

		values = (String[]) list.toArray(new String[0]);

		return values;
	}

}
